//
//  LZRecommendFollowViewController.m
//  LZBS
//
//  Created by 郝庆 on 16/6/8.
//  Copyright © 2016年 haoqing. All rights reserved.
//

#import "LZRecommendFollowViewController.h"
#import "LZHTTPSessionManager.h"
#import <SVProgressHUD.h>
#import "LZRecommendCategory.h"
#import "LZRecommendUser.h"
#import <MJExtension.h>
#import "LZRecommendCategoryCell.h"
#import "LZRecommendUserCell.h"
#import "LZRefreshHeader.h"
#import "LZRefreshFooter.h"

#define LZSelectedCategory self.categories[self.categoryTableView.indexPathForSelectedRow.row]

@interface LZRecommendFollowViewController ()<UITableViewDataSource,UITableViewDelegate>
/** 请求管理者 */
@property (nonatomic, weak) LZHTTPSessionManager *manager;
/** 左边的类别数据  */
@property (nonatomic, strong) NSArray *categories;
/** 左边类别的tableView */
@property (weak, nonatomic) IBOutlet UITableView *categoryTableView;
/** 右边用户的tableView */
@property (weak, nonatomic) IBOutlet UITableView *userTableView;
/** 请求参数 */
@property (nonatomic, strong) NSMutableDictionary *params;

@end

@implementation LZRecommendFollowViewController

static NSString * const LZCategoryCellId = @"category";
static NSString * const LZUserCellId = @"user";

/** manager属性的懒加载 */
- (LZHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [LZHTTPSessionManager manager];
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化设置
    [self setUpTableView];
    
    // 加载左侧的类别数据
    [self loadCategories];
    
    // 添加刷新控件
    [self setUpRefresh];
}

#pragma mark - 初始化设置
- (void)setUpTableView
{
    self.view.backgroundColor = LZCommonBgColor;
    self.navigationItem.title = @"推荐关注";
    
    // 注册
    [self.categoryTableView registerNib:[UINib nibWithNibName:NSStringFromClass([LZRecommendCategoryCell class]) bundle:nil] forCellReuseIdentifier:LZCategoryCellId];
    [self.userTableView registerNib:[UINib nibWithNibName:NSStringFromClass([LZRecommendUserCell class]) bundle:nil] forCellReuseIdentifier:LZUserCellId];
    
    // 设置inset
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.categoryTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    self.userTableView.contentInset = self.categoryTableView.contentInset;
    self.userTableView.rowHeight = 60;
    
}

#pragma mark - 加载左侧的类别数据
- (void)loadCategories
{
    // 请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"category";
    params[@"c"] = @"subscribe";
    
    // 显示指示器
    [SVProgressHUD show];
    
    __weak typeof(self) weakSelf = self;
    
    [self.manager GET:LZCommonURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        // 字典数组 -> 模型数组
        weakSelf.categories = [LZRecommendCategory mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        // 刷新表格
        [weakSelf.categoryTableView reloadData];
        
        // 默认选中第一行
        [weakSelf.categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
        
        // 让用户表格进入下拉刷新状态
        [weakSelf.userTableView.mj_header beginRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"当前网络不可用，请检查你的网络设置"];
    }];

}

#pragma mark - 添加刷新控件
- (void)setUpRefresh
{
     self.userTableView.mj_header = [LZRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewUsers)];

    self.userTableView.mj_footer = [LZRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUsers)];
    self.userTableView.mj_footer.hidden = YES;
}

/**
 *  下拉刷新
 */
- (void)loadNewUsers
{
    LZRecommendCategory *c = LZSelectedCategory;
    
    // 设置当前页码为1
    c.currentPage = 1;
    
    // 发送请求给服务器, 加载右侧的数据
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"] =  @(c.ID);
    params[@"page"] = @(c.currentPage);
    self.params = params;
    
    __weak typeof(self) weakSelf = self;
    
    [self.manager GET:LZCommonURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 字典数组 -> 模型数组
        NSArray *user = [LZRecommendUser mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        // 清除所有旧数据
        [c.users removeAllObjects];
        
        // 添加到当前类别对应的用户数组中
        [c.users addObjectsFromArray:user];
        
        // 保存总数
        c.total = [responseObject[@"total"] integerValue];
        
        // 不是最后一次请求
        if (weakSelf.params != params) return;
        
        // 刷新右边表格
        [weakSelf.userTableView reloadData];
        
        // 让底部控件结束刷新
        [weakSelf.userTableView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 提醒
        [SVProgressHUD showErrorWithStatus:@"当前网络不可用，请检查你的网络设置"];
        
        // 结束刷新
        [weakSelf.userTableView.mj_header endRefreshing];
    }];
}

/**
 *  上拉加载
 */
- (void)loadMoreUsers
{
    LZRecommendCategory *category = LZSelectedCategory;
    
    // 发送请求给服务器, 加载右侧的数据
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"] = @(category.ID);
    params[@"page"] = @(++category.currentPage);
    self.params = params;
    
    __weak typeof(self) weakSelf = self;
    
    [self.manager GET:LZCommonURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 字典数组 -> 模型数组
        NSArray *user = [LZRecommendUser mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        // 添加到当前类别对应的用户数组中
        [category.users addObjectsFromArray:user];
        
        // 不是最后一次请求
        if (weakSelf.params != params) return;
        
        // 刷新右边表格
        [weakSelf.userTableView reloadData];
        
        // 让底部控件结束刷新
        [weakSelf checkFooterState];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"当前网络不可用，请检查你的网络设置"];
        
        // 让底部控件结束刷新
        [weakSelf.userTableView.mj_footer endRefreshing];
    }];
}

/**
 * 时刻监测footer的状态
 */
- (void)checkFooterState
{
    LZRecommendCategory *rc = LZSelectedCategory;
    
    // 每次刷新右边数据时, 都控制footer显示或者隐藏
    self.userTableView.mj_footer.hidden = (rc.users.count == 0);
    
    // 让底部控件结束刷新
    if (rc.users.count == rc.total) { // 全部数据已经加载完毕
        [self.userTableView.mj_footer endRefreshingWithNoMoreData];
    } else { // 还没有加载完毕
        [self.userTableView.mj_footer endRefreshing];
    }
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // 左边的类别表格
    if (tableView == self.categoryTableView) return self.categories.count;
    
    // 监测footer的状态
    [self checkFooterState];
    
    // 右边的用户表格
    return [LZSelectedCategory users].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.categoryTableView) { // 左边的类别表格
        LZRecommendCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:LZCategoryCellId];
        cell.category = self.categories[indexPath.row];
        return cell;
    } else { // 右边的用户表格
        LZRecommendUserCell *cell = [tableView dequeueReusableCellWithIdentifier:LZUserCellId];
        LZRecommendCategory *c = LZSelectedCategory;
        cell.user = c.users[indexPath.row];
        return cell;
    }
}

#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 结束刷新
    [self.userTableView.mj_header endRefreshing];
    [self.userTableView.mj_footer endRefreshing];
    
    LZRecommendCategory *c = self.categories[indexPath.row];
    if (c.users.count) {
        
        [self.userTableView reloadData];
        
    } else {
        
        // 防止网速慢,赶紧刷新表格,马上显示当前category的用户数据, 不让用户看见上一个category的残留数据
        [self.userTableView reloadData];
        
        // 进入下拉刷新状态
        [self.userTableView.mj_header beginRefreshing];
        
    }
}

#pragma mark - 控制器的销毁
- (void)dealloc
{
    // 停止所有操作
    [self.manager.operationQueue cancelAllOperations];
}

@end
